package org.budo.graph.druid.filter.connection;

import java.sql.Connection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.pool.DruidPooledConnection;

/**
 * @author limingwei
 */
public class AbstractActiveConnectionFilter extends FilterAdapter {
    private final Map<Connection, Object> activeConnections = new IdentityHashMap<Connection, Object>();

    protected Map<Connection, Object> getActiveConnections() {
        return this.activeConnections;
    }

    /**
     * 获取未回收的连接
     */
    public Map<Connection, Object> getActiveConnectionsCopy() {
        synchronized (this.activeConnections) {
            return new HashMap<Connection, Object>(this.getActiveConnections()); // 复制一份
        }
    }

    /**
     * 加锁
     */
    protected void putActiveConnection(DruidPooledConnection connection, Object activeConnectionProfiler) {
        synchronized (this.activeConnections) {
            this.getActiveConnections().put(connection, activeConnectionProfiler);
        }
    }

    protected void removeActiveConnection(DruidPooledConnection connection) {
        synchronized (this.activeConnections) {
            this.getActiveConnections().remove(connection);
        }
    }
}